package com.itheima.reggie.filters;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
@WebFilter("/**")
public class LoginFilter implements Filter {
    // spring 提供的路径匹配器 （支持通配符）
    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 请求和响应 转化成 Http请求和响应对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 获取本次请求的URI
        String requestURI = req.getRequestURI();
        log.info("本次请求路径是：{}", requestURI);

        // 判断本次请求, 是否需要登录, 才可以访问
        //定义不需要处理的请求路径
        String uris[] = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/sms/*",
                "/user/sms/send",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "swagger-ui.html"
        };

        //路径校验：如果请求路径在范围内放行，否则进入下一步
        if (math(uris, requestURI)) {
            log.info("本次请求不需要处理，已放行....：{}", requestURI);
            chain.doFilter(req, resp);
            return;
        }
        // 判断员工登录状态，如果已登录，则直接放行  user
        Object employee = req.getSession().getAttribute("employee");
        if (!Objects.isNull(employee)) {
            log.info("员工已登录，放行....");
            // 把登录过的employeeId放到ThreadLocal中
            ThreadLocalUtils.set((Long) employee);
            log.info("给线程绑定的id:{}", ThreadLocalUtils.get());
            System.out.println("--->" + Thread.currentThread().getId());
            chain.doFilter(req, resp);
            // 把登录过的employeeId从ThreadLocal移除
            ThreadLocalUtils.remove();
            return;
        }

        // 判断用户登录状态，如果已登录，则直接放行
        Long userId = (Long) req.getSession().getAttribute("user");
        if (!Objects.isNull(userId)) {
            log.info("用户已登录，放行....");
            // 把登录过的userId放到ThreadLocal中
            ThreadLocalUtils.set(userId);
            log.info("给线程绑定的id:{}", ThreadLocalUtils.get());
            System.out.println("--->" + Thread.currentThread().getId());
            chain.doFilter(req, resp);
            // 把登录过的employeeId从ThreadLocal移除
            ThreadLocalUtils.remove();
            return;
        }
        // 如果未登录, 则返回未登录结果
        log.info("用户未登录，跳转到登录页面...");
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    public Boolean math(String[] urls, String requestURI) {
        for (String uri : urls) {
            boolean result = ANT_PATH_MATCHER.match(uri, requestURI);
            if (result) {
                return true;
            }
        }
        return false;
    }
}